//
//  RSImgVScrollView.m
//  RSUIScrollView
//
//  Created by thinkjoy on 16/8/26.
//  Copyright © 2016年 Thinkjoy_RS. All rights reserved.
//

#import "RSImgVScrollView.h"
#import "UIImageView+WebCache.h"

#define PageControl_H   30
#define MainScrollView_W    (self.mainScrollView.frame.size.width)
#define MainScrollView_H    (self.mainScrollView.frame.size.height)
#define MainScrollView_ImgsCount    3

#define Self_W  (self.frame.size.width)
#define Self_H  (self.frame.size.height)

#pragma mark - 日志开关
#ifdef DEBUG
#define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define DLog(...)
#endif

@interface RSImgVScrollView ()<UIScrollViewDelegate>

@property   (nonatomic,strong)  UIScrollView    * mainScrollView;
@property   (nonatomic,strong)  UIPageControl   * mainPageControl;

@property   (nonatomic,strong)  NSTimer * timer;    //定时器

@property   (nonatomic,strong)  NSArray * imgAry;   //图片数组
/**总页数*/
//@property   (nonatomic,assign)  NSInteger  allPages;

/**当前页数*/
@property   (nonatomic,assign)  NSInteger  centerSelectedPage;


@end

@implementation RSImgVScrollView
- (instancetype)initWithFrame:(CGRect)frame
{
    self    =   [super initWithFrame:frame];
    if (self) {
        self.backgroundColor    =   [UIColor redColor];
        _bounces            =   YES;
        self.hidePageControlForSinglePages = YES;
        _centerSelectedPage    =   0;
        
        self.clipsToBounds = YES;   //剪切超过父视图的部分
        [self   addSubview:self.mainScrollView];
        [self   addSubview:self.mainPageControl];
    }
    return self;
}
- (void) layoutSubviews
{
    //    [self initialize];
    self.mainScrollView.frame   =   CGRectMake(0, 0, Self_W, Self_H);
    [self setupPageControllPosition];
    [self setupScrollViewContentSize];
    [self setupNumberOfPages];
    [self updateContent];
    [self startTimer];
}

/**
 *  scrollView初始化
 *
 */
- (UIScrollView *)mainScrollView
{
    if (_mainScrollView==nil) {
        _mainScrollView = [[UIScrollView alloc] init];
        _mainScrollView.backgroundColor =   [UIColor whiteColor];
        _mainScrollView.delegate = self;
        _mainScrollView.pagingEnabled = YES;
        _mainScrollView.bounces = _bounces;
        _mainScrollView.showsHorizontalScrollIndicator = NO;
        _mainScrollView.showsVerticalScrollIndicator = NO;
        _mainScrollView.autoresizingMask = self.autoresizingMask;
        
        //增加子控件
        for(NSInteger i = 0; i < MainScrollView_ImgsCount; i++)
        {
            UIImageView *imageView = [[UIImageView alloc]init];
            imageView.frame =   CGRectMake(i*Self_W, 0, Self_W, Self_H);
//            imageView.tag   =   (i+1)*10;
            imageView.userInteractionEnabled = YES;
            [_mainScrollView addSubview:imageView];
            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageClick:)]];
        }
    }
    return _mainScrollView;
}
#pragma mark - 手势点击imageView
- (void)imageClick:(UITapGestureRecognizer *)tap
{
    DLog(@"点击了");
    if([_delegate respondsToSelector:@selector(imgVScrollView:didSelectImageAtIndex:)]) {
        [self.delegate imgVScrollView:self didSelectImageAtIndex:_centerSelectedPage];
    }
}

/**
 *  pageControl初始化
 *
 */
- (UIPageControl *)mainPageControl{
    if (_mainPageControl==nil) {
        _mainPageControl = [[UIPageControl alloc] init];
        _mainPageControl.userInteractionEnabled = NO;
        [self addSubview:_mainPageControl];
        
        //        _mainPageControl.hidden =   !_showPageControl;
    }
    return _mainPageControl;
}

/**
 *  设置contentSize大小
 */
- (void)setupScrollViewContentSize
{
    NSArray *imageOrUrlAry = (NSArray *)[_dataSource arrayWithImagesInImgVScrollView:self]; //得到数据源数组
    _imgAry =   imageOrUrlAry;
    _mainScrollView.contentSize = CGSizeMake(MainScrollView_W * MainScrollView_ImgsCount, 0);
    _mainScrollView.contentOffset = CGPointMake(MainScrollView_W, 0);
}

/**
 *  设置PageControll的位置
 */
- (void)setupPageControllPosition
{
    CGRect pageControlFrame = CGRectMake(0, 0, MainScrollView_W, PageControl_H);
    self.mainPageControl.frame  =   pageControlFrame;
    switch (self.pageControllPosition) {
        case RSImgVScrollViewPageControllPositionCenter:
        {
            _mainPageControl.center = CGPointMake(MainScrollView_W / 2, MainScrollView_H - 12.0);
        }
            break;
        case RSImgVScrollViewPageControllPositionLeft:
        {
            _mainPageControl.center = CGPointMake(MainScrollView_W / 4, MainScrollView_H - 12.0);
        }
            break;
        case RSImgVScrollViewPageControllPositionRight:
        {
            _mainPageControl.center = CGPointMake(MainScrollView_W*3 / 4, MainScrollView_H - 12.0);
        }
            break;
        case RSImgVScrollViewPageControllPositionHidden:
        {
        }
            break;
        default:
            break;
    }
    _mainPageControl.hidden =   [self setupPageControlShowOrHidden];
}


/**
 *  设置pageControlCurrent
 */
- (void)setupNumberOfPages
{
    _mainPageControl.numberOfPages    =   _imgAry.count;
}

/**
 *  更新图片内容,数组为0时显示有默认图片显示默认图片
 */
- (void)updateContent
{
    if (_imgAry.count>0) {
        // 更新imageView上面的图片内容
        for (NSInteger i = 0; i < MainScrollView_ImgsCount; i++) { // i是用来获取imageView的
            UIImageView *imageView = _mainScrollView.subviews[i];
            
            // 根据当前页码求出imageIndex
            NSInteger imageIndex = 0;
            if (i==0) { // 左边
                imageIndex = _centerSelectedPage - 1;
                
                if (imageIndex == -1) { // 显示最后面一张
                    imageIndex = self.imgAry.count - 1;
                }
                
            } else if (i==1) { // 中间
                
                imageIndex = _centerSelectedPage;
                
            } else if (i==2) { // 右边
                imageIndex = _centerSelectedPage + 1;
                if (imageIndex == self.imgAry.count) { // 显示最前面一张
                    imageIndex = 0;
                }
            }
            
            imageView.tag = imageIndex;
            
//            DLog(@"index = %d , imgV=%@",imageIndex,imageView);
            // 图片数据
            [self loadImage:imageIndex withImageView:imageView];
            //        [self addImageAtImageView:(UIImageView *)imageView];
        }
        
         _mainPageControl.hidden =   [self setupPageControlShowOrHidden];
        
//        self.mainScrollView.scrollEnabled = YES;
        self.mainScrollView.scrollEnabled   =   [self setupImgVScrollViewWhetherScroll];
    }else{
        for (NSInteger i = 0; i < MainScrollView_ImgsCount; i++) { // i是用来获取imageView的
            UIImageView *imageView = _mainScrollView.subviews[i];
            if ([self.dataSource respondsToSelector:@selector(placeHolderImageForImgVScrollView)]) {
                imageView.image =   [self.dataSource placeHolderImageForImgVScrollView];
            }
            if ([self.dataSource respondsToSelector:@selector(placeHolderImageVContentModeForImgVScrollView)]) {
                imageView.contentMode   =   [self.dataSource placeHolderImageVContentModeForImgVScrollView];
            }
        }
//        self.mainPageControl.hidden =   YES;
         _mainPageControl.hidden =   [self setupPageControlShowOrHidden];
//        self.mainScrollView.scrollEnabled = NO;
        self.mainScrollView.scrollEnabled   =   [self setupImgVScrollViewWhetherScroll];
    }
}

/**
 *  加载图片
 *
 *  @param imageIndex 图片在数组中的索引
 *  @param imageView  添加图片的imageView
 */
- (void)loadImage:(NSInteger)imageIndex withImageView:(UIImageView *)imageView
{
    imageView.contentMode   =   [self.dataSource imgVScrollView:self contentModeForImgAtIndex:imageIndex];
    id obj = self.imgAry[imageIndex];
    if ([obj isKindOfClass:[UIImage class]]) { // UIImage对象
        imageView.image = obj;
    } else if ([obj isKindOfClass:[NSData class]]){//NSData数据
        imageView.image =   [UIImage imageWithData:obj];
    } else if ([obj isKindOfClass:[NSString class]]) { // 本地图片名
        imageView.image = [UIImage imageNamed:obj];
    } else if ([obj isKindOfClass:[NSURL class]]) { // 远程图片URL
        UIImage * placeHolderImg = nil;
        if ([self.dataSource respondsToSelector:@selector(imgVScrollView:placeHolderImageAtIndex:)]) {
            placeHolderImg    =   [self.dataSource imgVScrollView:self placeHolderImageAtIndex:imageIndex];
        }
        [imageView sd_setImageWithURL:obj placeholderImage:placeHolderImg];
    }
    
}


#pragma mark    UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 找出显示在最中间的imageView
    UIImageView *middleImageView = nil;
    // x值和偏移量x的最小差值
    CGFloat minDelta = MAXFLOAT;
    for (NSInteger i = 0; i < MainScrollView_ImgsCount; i++) {
        UIImageView *imageView = self.mainScrollView.subviews[i];
        
        // x值和偏移量x差值最小的imageView，就是显示在最中间的imageView
        CGFloat currentDelta = 0;
        currentDelta = ABS(imageView.frame.origin.x - self.mainScrollView.contentOffset.x);
        
        if (currentDelta < minDelta)
        {
            minDelta = currentDelta;
            middleImageView = imageView;
//            NSLog(@"%d",middleImageView.tag);
        }
        _centerSelectedPage = middleImageView.tag;
        
        //去掉重影
        if (i==MainScrollView_ImgsCount-1) {
            self.mainPageControl.currentPage    =   _centerSelectedPage;
        }
//
        
    }
//    self.mainPageControl.currentPage
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self updateContent];
    [self.mainScrollView setContentOffset:CGPointMake(MainScrollView_W, 0) animated:NO];
    self.mainPageControl.currentPage    =   _centerSelectedPage;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self startTimer];
}

#pragma mark    定时器方法
- (void)setIntervalTime:(NSTimeInterval)intervalTime
{
    _intervalTime   =   intervalTime;
    [self startTimer];
}

- (void)startTimer
{
    if (self.intervalTime && [self setupImgVScrollViewWhetherAutomaticScroll]) {
        [self stopTimer];
        
        self.timer =[NSTimer scheduledTimerWithTimeInterval:self.intervalTime target:self selector:@selector(nextImage:) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }else{
        [self stopTimer];
    }
}

- (void)stopTimer
{
    if([self.timer isValid]) {
        [self.timer invalidate];
    }
    self.timer =nil;
}

/**
 *  自定义设置分页指示器的颜色
 *
 *  @param currentColor 选中得颜色
 *  @param otherColor   其他颜色
 */
- (void)setpageControlCurrentColor:(UIColor *)currentColor OtherColor:(UIColor *)otherColor
{
    if(!currentColor || !otherColor)  return;
    
    self.mainPageControl.currentPageIndicatorTintColor = currentColor;
    self.mainPageControl.pageIndicatorTintColor = otherColor;
}

- (void)nextImage:(NSTimer *)timer
{
    static BOOL singleLoop= YES;
    static NSInteger offSet_W    =   -1;
    DLog(@"自动滑动");
    __weak typeof(self)weakSelf = self;
    CGPoint offSetPoint ;
    switch (self.scrollType) {
        case RSImgVScrollViewRollingTypeInfiniteLoopLeft:
        {
            offSetPoint =   CGPointMake(2 * MainScrollView_W, 0);
        }
            break;
        case RSImgVScrollViewRollingTypeInfiniteLoopRight:
        {
            offSetPoint =   CGPointMake(0 , 0);
        }
            break;
        case RSImgVScrollViewRollingTypeSingleLoop:
        {
//            offSetPoint =   CGPointMake(2 * MainScrollView_W, 0);
            if (self.imgAry.count>1) {
                
                if (_centerSelectedPage == 0 || _centerSelectedPage == self.imgAry.count-1) {
                    offSet_W = offSet_W * (-1);
                }
                offSetPoint =   CGPointMake(self.mainScrollView.contentOffset.x + offSet_W*MainScrollView_W, 0);
                
            }else if (self.imgAry.count == 1){
                if (singleLoop) {
                    offSetPoint =   CGPointMake(2 * MainScrollView_W, 0);
                }else{
                    offSetPoint =   CGPointMake( 0, 0);
                }
                singleLoop = !singleLoop;
            }
            
        }
            break;
        case RSImgVScrollViewRollingTypeunabledLoop:
        {
            offSetPoint =   CGPointMake(2 * MainScrollView_W, 0);
        }
            break;
        default:
            break;
    }
    [UIView animateWithDuration:0.25 animations:^{
        weakSelf.mainScrollView.contentOffset = offSetPoint;
    } completion:^(BOOL finished) {
        [weakSelf updateContent];
        [weakSelf setupScrollViewContentSize];
    }];
}

#pragma mark    属性的Set方法
//轮播图滑到边界时是否可以继续滑动,YES=可以,NO=不可以,默认为YES
- (void)setBounces:(BOOL)bounces
{
    _bounces    =   bounces;
    _mainScrollView.bounces =   _bounces;
}


// PageControll的位置,默认,底部中心
- (void)setPageControllPosition:(RSImgVScrollViewPageControllPosition)pageControllPosition
{
    _pageControllPosition = pageControllPosition;
    [self setupPageControllPosition];
}

//轮播图只有一张图片时,是否隐藏指示器(UIPageControl),YES=隐藏,NO=显示,默认隐藏
- (void) setHidePageControlForSinglePages:(BOOL)hidePageControlForSinglePages
{
    _hidePageControlForSinglePages = hidePageControlForSinglePages;

     _mainPageControl.hidden =   [self setupPageControlShowOrHidden];
    
//    if ([(NSArray *)[_dataSource arrayWithImagesInImgVScrollView:self] count] == 1) {
//        self.mainPageControl.hidden = hidePageControlForSinglePages;
//    }
}

/**
 *  根据图片数组数量,hidePageControlForSinglePages,pageControllPosition来判断是否隐藏PageControl
 *
 *  @return YES=隐藏,NO=显示
 */
- (BOOL)setupPageControlShowOrHidden
{
    if (self.pageControllPosition == RSImgVScrollViewPageControllPositionHidden) {
        return YES;
    }else{
        if (_imgAry.count==1) {
            return self.hidePageControlForSinglePages;
        }else if (_imgAry.count==0){
            return YES;
        }
    }
    return NO;
}

/**轮播图只有一张图片时,是否允许继续轮播,YES=允许,NO=禁止,默认YES*/
- (void)setScrollEnabledForSinglePages:(BOOL)scrollEnabledForSinglePages
{
    _scrollEnabledForSinglePages    =   scrollEnabledForSinglePages;
}

/** RSImgVScrollView滚动类型,默认无限向左滚动 */
- (void)setScrollType:(RSImgVScrollViewRollingType)scrollType
{
    _scrollType =   scrollType;
}

/**
 *  是否允许scrollerView滚动
 *  根据图片数组数量,RSImgVScrollViewRollingType,scrollEnabledForSinglePages来判断是否允许scrollerView滚动
 *
 *  @return YES=滚动,NO=不滚动
 */
- (BOOL)setupImgVScrollViewWhetherScroll
{
    if (_imgAry.count==0) {
        return NO;
    }else if (_imgAry.count == 1){
        return self.scrollEnabledForSinglePages;
//        if (self.scrollEnabledForSinglePages) {
//            return YES;
//        }else{
//            return NO;
//        }
    }else{
        return YES;
    }
//    return YES;
}

/**
 *  是否允许scrollerView自动滚动
 *  根据setupImgVScrollViewWhetherScroll,RSImgVScrollViewRollingType来判断是否允许scrollerView自动滚动
 *
 *  @return YES=滚动,NO=不滚动
 */
- (BOOL)setupImgVScrollViewWhetherAutomaticScroll
{
    if ([self setupImgVScrollViewWhetherScroll]) {
        if (self.scrollType != RSImgVScrollViewRollingTypeunabledLoop) {
            return YES;
        }else{
            return NO;
        }
    }else{
        return NO;
    }
}

@end
